// 和广告功能相关的路由地址接口
let { uploadimg } = require("../util");
const express = require("express");
let router = express.Router();
const advModel = require("../models/advModel");

router.get("/getadvdata", async (req, res) => {
  // 获取广告信息
  try {
    let advsData = await advModel.find();
// 分页
let totalCount=advsData.length
// 每页显示的条数 
let perpage = 3;
// 计算页码
let pageCount = Math.ceil( totalCount/perpage);
let {p}=req.query
console.log(p,'这里')
    console.log(advsData);
let filterData=await advModel.find().skip((p-1)*perpage).limit(perpage)

    res.json({
      info: "获取广告信息成功",
      status: 1,
      pageCount,
      advs: filterData,
    });
  } catch (err) {
    res.json({
      info: "获取广告信息失败",
      status: 0,
      err,
    });
  }
});

router.post("/addadv", async (req, res) => {
  console.log(req.body);
  try {
    let reslut = await uploadimg(req);
    console.log(reslut);

    reslut.time = new Date().toLocaleDateString();
    console.log(reslut);
    //    把密码加密之后添加到数据库
    let resobj = await advModel.create(reslut);
    console.log(resobj);
    res.json({
      info: "添加广告成功",
      status: 1,
    });
  } catch (err) {
    res.json({
      info: "添加广告失败",
      status: 0,
      err,
    });
  }
});


// // 删除广告信息
router.delete("/deladv", async (req, res) => {
  // 获取delete 传递过来的id数据
  let { _id } = req.query;
  console.log(_id);
  try {
    // 通过 id 删除 数据库里对应的数据
    let resobj = await advModel.deleteOne({ _id });
    console.log(resobj);
    res.json({
      info: "删除广告成功",
      status: 1,
      resobj,
    });
  } catch (err) {
    res.json({
      info: "删除广告失败",
      status: 0,
      err,
    });
  }
});



module.exports = router;
